package cn.com.xinjinfu.pdoulcProduct.activity.user;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.NumberFormat;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import cn.com.xinjinfu.pdoulcProduct.R;
import cn.com.xinjinfu.pdoulcProduct.activity.base.BaseActivity;
import cn.com.xinjinfu.pdoulcProduct.engine.DataHandler;
import cn.com.xinjinfu.pdoulcProduct.entity.ActRechargeBean;
import cn.com.xinjinfu.pdoulcProduct.entity.BanksCardBean;
import cn.com.xinjinfu.pdoulcProduct.entity.User;
import cn.com.xinjinfu.pdoulcProduct.manager.AccountManager;
import cn.com.xinjinfu.pdoulcProduct.manager.L;
import cn.com.xinjinfu.pdoulcProduct.manager.TitleManager;
import cn.com.xinjinfu.pdoulcProduct.manager.UIManager;
import cn.com.xinjinfu.pdoulcProduct.utils.BankImgUtils;
import cn.com.xinjinfu.pdoulcProduct.utils.ReloadUserInfo;
import cn.com.xinjinfu.pdoulcProduct.utils.lianlianpay.BaseHelper;
import cn.com.xinjinfu.pdoulcProduct.utils.lianlianpay.Constants;
import cn.com.xinjinfu.pdoulcProduct.utils.lianlianpay.MobileSecurePayer;

/**
 * 绑定新的银行卡
 * Created by android-adt on 2016/3/1.
 */
public class BankBangdingAct extends BaseActivity implements AdapterView.OnItemClickListener {
    private Dialog dg;
    private RequestQueue requen;
    private RelativeLayout rl_select_number;
    private List<BanksCardBean.SupportBanks> banksList;
    private BanksCardBean.SupportBanks supportBanks;
    private User user;
    private String mBank, mBankCode, mBankNum;
    private EditText tv_carnum;
    private Button affirm_buy;
    private TextView tv_bankcart, tv_error_hint;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_bankcard_add);
        TitleManager.showTitle(this, "银行卡", "");
        user = AccountManager.getInstance().getUser();
        requen = Volley.newRequestQueue(this);
        rl_select_number = (RelativeLayout) findViewById(R.id.rl_select_number);
        rl_select_number.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginBankcardRequest();
            }
        });
        tv_bankcart = (TextView) findViewById(R.id.tv_bankcart);
        tv_carnum = (EditText) findViewById(R.id.tv_carnum);
        tv_carnum.addTextChangedListener(mTextWatcher);
        tv_error_hint = (TextView) findViewById(R.id.tv_error_hint);
        affirm_buy = (Button) findViewById(R.id.affirm_buy);
        affirm_buy.setEnabled(false);
        affirm_buy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginRequest();
            }
        });
    }


    /**
     * 银行卡列表请求网络*
     */
    private void loginBankcardRequest() {
        final Map<String, String> parameters = DataHandler.getParameters("1302");
        dg = UIManager.getLoadingDialog(this);
        dg.setCanceledOnTouchOutside(true);
        dg.show();
        JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null, succeedBankRespon, error);
        requen.add(request);
    }

    private Response.ErrorListener error = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            dg.dismiss();
            DataHandler.errorHandler(BankBangdingAct.this, error);
        }
    };

    private Response.Listener<JSONObject> succeedBankRespon = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jobj) {
            dg.dismiss();
            L.i("succeedBankRespon=============" + jobj.toString());
            BanksCardBean banksCardBean = JSON.parseObject(jobj.toString(), BanksCardBean.class);
            banksList = banksCardBean.getSupportBanks();
            showBankcardDialog();
        }
    };

    /**
     * 支付 网络请求
     */
    private void loginRequest() {
        if (user != null) {
            final Map<String, String> parameters = DataHandler.getParameters("1301");
            parameters.put("id", user.getCurrUser().getSign());
            parameters.put("rechargeType", "2");
            parameters.put("rechargeAmount", "0.01");
            parameters.put("card_no", tv_carnum.getText().toString());
            parameters.put("bankCode", mBankCode);
            parameters.put("single_amt", supportBanks.getSingle_amt() + "");
            parameters.put("day_amt", supportBanks.getDay_amt() + "");
            parameters.put("month_amt", supportBanks.getMonth_amt() + "");
            JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null, lianlianRespon, null);
            requen.add(request);
        }
    }

    private Response.Listener<JSONObject> lianlianRespon = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jobj) {
            L.i(jobj.toString());
            ActRechargeBean actRechargeBean = JSON.parseObject(jobj.toString(), ActRechargeBean.class);
            if (actRechargeBean.getCode() == -1) {
                ActRechargeBean.Jsonresult jsonresult = actRechargeBean.getJsonresult();
                JSONObject jsonresult0 = null;
                String acct_name = strUTF8Name(jsonresult.getAcct_name());
                try {
                    jsonresult0 = jobj.getJSONObject("jsonresult");
                    jsonresult0.put("acct_name", acct_name);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                L.d("跳转到连连支付平台");
                MobileSecurePayer msp = new MobileSecurePayer();
                boolean bRet = msp.pay(jsonresult0.toString(), mHandler,
                        Constants.RQF_PAY, BankBangdingAct.this, false);
            } else {
                tv_error_hint.setText(actRechargeBean.getMsg());
            }
        }

    };
    private Handler mHandler = createHandler();

    private Handler createHandler() {
        return new Handler() {
            public void handleMessage(Message msg) {
                String strRet = (String) msg.obj;
                switch (msg.what) {
                    case Constants.RQF_PAY: {
                        JSONObject objContent = BaseHelper.string2JSON(strRet);
                        String retCode = objContent.optString("ret_code");
                        String retMsg = objContent.optString("ret_msg");
                        String no_order = objContent.optString("no_order");
                        String result_pay = objContent.optString("result_pay");
                        String money_order = objContent.optString("money_order");
                        try {
                            objContent.put("ret_msg", "");
                            objContent.put("ret_code", "");
                            objContent.put("agreementno", "");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        L.d("json=================" + objContent.toString());
                        // TODO 先判断状态码，状态码为 成功或处理中 的需要 验签
                        if (Constants.RET_CODE_SUCCESS.equals(retCode)) {
                            String resulPay = objContent.optString("result_pay");
                            if (Constants.RESULT_PAY_SUCCESS.equalsIgnoreCase(resulPay)) {
                                // TODO 支付成功后续处理
                                dg = UIManager.getLoadingDialog(BankBangdingAct.this);
                                dg.setCanceledOnTouchOutside(false);
                                dg.show();
                                final Map<String, String> parameters = DataHandler.getParameters("1308");
                                parameters.put("no_order", no_order);
                                parameters.put("result_pay", result_pay);
                                parameters.put("money_order", money_order);
                                parameters.put("res_data", objContent.toString());
                                TimerTask task = new TimerTask() {
                                    public void run() {
                                        JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null, succeedRespon, error);
                                        requen.add(request);
                                    }
                                };
                                Timer timer = new Timer();
                                timer.schedule(task, 1000);
                            }else {
                                UIManager.showSuccessDilog(BankBangdingAct.this, R.drawable.img_doucry,1, "绑卡失败", "确定", null);
                            }
                        }else {
                            UIManager.showSuccessDilog(BankBangdingAct.this, R.drawable.img_doucry,1, "绑卡失败", "确定", null);
                        }
                    }
                    break;
                }
                super.handleMessage(msg);
            }
        };

    }
    /**
     * 这是连连充值成功后  服务后台验签 返回结果
     */
    private Response.Listener<JSONObject> succeedRespon = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jobj) {
            L.d("-----------绑卡验签结果-----------------"+jobj.toString());
            dg.dismiss();
            /****延时3秒***刷新user****/
            TimerTask task = new TimerTask() {
                public void run() {
                    new ReloadUserInfo(BankBangdingAct.this).userRequest();
                }
            };
            Timer timer = new Timer();
            timer.schedule(task, 2000);

            UIManager.showSuccessDilog(BankBangdingAct.this, R.drawable.img_douhappy,0, "绑卡成功！", "确定", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Message msg = new Message();
                    msg.what = 101;
                    handler.sendMessage(msg);
                }
            });
        }
    };

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 101:
                    dg.show();
                    TimerTask task = new TimerTask() {
                        public void run() {
                            dg.dismiss();
                            finish();
                            startActivity(new Intent(BankBangdingAct.this, ActBankControl.class));
                        }
                    };
                    Timer timer = new Timer();
                    timer.schedule(task, 2000);
                    break;
            }
        }
    };

    public float dp2px(float dp) {
        final float scale = getResources().getDisplayMetrics().density;
        return dp * scale + 0.5f;
    }
    /**
     * 银行卡PopupWindow
     */
    private ListView lv;
    private PopupWindow pw;
    private BankCartAdapter adapter;

    private void showBankcardDialog() {
        lv = new ListView(this);
        lv.setBackgroundResource(R.drawable.listview_background);
        lv.setDividerHeight(0);
        lv.setVerticalScrollBarEnabled(true);
        adapter = new BankCartAdapter();
        L.i("banksList=============" + banksList.toString());
        adapter.setList(banksList);
        adapter.notifyDataSetChanged();
        lv.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        lv.setOnItemClickListener(this);
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;
        int height = metric.heightPixels - (int)dp2px(159.5f);
        pw = new PopupWindow(lv, width, height);
        pw.setOutsideTouchable(true);
        pw.setBackgroundDrawable(new BitmapDrawable());
        pw.setFocusable(true);
        pw.showAtLocation(rl_select_number, Gravity.BOTTOM, 0, 1);
    }

    class BankCartAdapter extends BaseAdapter {
        private List<BanksCardBean.SupportBanks> banksList;

        public void setList(List<BanksCardBean.SupportBanks> banksList) {
            this.banksList = banksList;
        }

        @Override
        public int getCount() {
            return banksList == null ? 0 : banksList.size();
        }

        @Override
        public Object getItem(int position) {
            return banksList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = View.inflate(BankBangdingAct.this, R.layout.bankcart_item, null);
                holder.tvNumber = (TextView) convertView.findViewById(R.id.tv_number);
                holder.bank_info = (TextView) convertView.findViewById(R.id.bank_info);
                holder.imgBankcard = (ImageView) convertView.findViewById(R.id.img_bankcard);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            BanksCardBean.SupportBanks supportBanks = banksList.get(position);
            if (banksList != null) {
                holder.tvNumber.setText(supportBanks.getBank_name());
                int x = new BankImgUtils().mBank(false, supportBanks.getBank_code());
                holder.imgBankcard.setImageResource(x);

                if (supportBanks.getBank_status().equals("2")){
                    holder.bank_info.setText("该银行在维护中，暂不支持充值");
                }else {
                    holder.bank_info.setText("*单笔限额" + NumberFormat.getInstance().format(supportBanks.getSingle_amt() / 10000) +
                            "万元，每日限额" + NumberFormat.getInstance().format(supportBanks.getDay_amt() / 10000) + "万元");
                }
            }
            return convertView;
        }

        class ViewHolder {
            public TextView tvNumber;
            public ImageView imgBankcard;
            public TextView bank_info;
        }
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        supportBanks = banksList.get(position);
        if(supportBanks.getBank_status().equals("2")){
            return;
        }else {
            mBank = supportBanks.getBank_name();
            mBankCode = supportBanks.getBank_code();
            pw.dismiss();
            UIManager.showBankInfo(this, supportBanks, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    findViewById(R.id.rl_account_num).setVisibility(View.VISIBLE);
                    tv_bankcart.setText(mBank);
                    tv_bankcart.setTextColor(0xff333333);
                }
            });
        }
    }


    /**
     * URLdecode姓名转换成utf——8
     */
    public String strUTF8Name(String URLdecode) {
        String strUTF8 = null;
        try {
            strUTF8 = URLDecoder.decode(URLdecode, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        L.d("=====================================" + strUTF8);
        return strUTF8;
    }

    TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
        }

        @Override
        public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            tv_error_hint.setText("");
            mBankNum = tv_carnum.getText().toString();
            if (TextUtils.isEmpty(tv_carnum.getText())) {
                affirm_buy.setEnabled(false);
            } else {
                affirm_buy.setEnabled(true);
            }
        }
    };
}
